#!groovy
pipeline {
  agent any
  stages {
    stage('初始化') {
      steps {
        echo "【信息】打印环境变量初始值"
        sh "printenv"

        echo "【信息】Job全部参数：${params}"

        script {
          Common = load './common/common.groovy'
          Common.applicationRootAbsolute = Common.getApplicationRootAbsolute(params.APPLICATION_ROOT_DIR)
        }

        // 拉取部署文件
        dir(Common.pipelineCicdDir) {
          git env.GIT_URL
        }

        // 拉取应用代码，需要安装插件git parameter
        git branch: params.APPLICATION_GIT_BRANCH, url: params.APPLICATION_GIT_URL

        dir(Common.applicationRootAbsolute) {
          script {
            Common.cicdYamlData = Common.readCicdYaml(params.ENV_OPTION, Common.applicationRootAbsolute)
          }
        }
      }
    }
    stage("部署Docker镜像") {
      steps {
        dir(Common.applicationRootAbsolute) {
          script {
            for (int i = 0; i < Common.cicdYamlData.envData.ipArr.length; i++) {
              def serverIp = Common.cicdYamlData.envData.ipArr[i]
              sh """
                ssh root@${serverIp} "
                    oldImagesIds=\\\$(docker images | grep ${Common.cicdYamlData.applicationName} | awk '{print \\\$3}');
                    docker pull ${env.DOCKER_IMAGE};
                    docker container stop ${Common.cicdYamlData.applicationName};
                    docker container rm ${Common.cicdYamlData.applicationName};
                    ${Common.cicdYamlData.envData.dockerRunCommand};
                    docker rmi \\\$oldImagesIds || true;"
              """
            }
          }
        }
      }
    }
  }
  post {
    success {
      script {
        if (Common.cicdYamlData.notice.wx.ciSuccessSend || Common.cicdYamlData.notice.wx.cdSuccessSend) {
          Common.curlWx(Common.cicdYamlData.notice.wx.key, env.JOB_NAME, Common.cicdYamlData.envData.envName, true)
        }
      }
    }
    failure {
      script {
        if (Common.cicdYamlData.notice.wx.ciFailureSend || Common.cicdYamlData.notice.wx.cdFailureSend) {
          Common.curlWx(Common.cicdYamlData.notice.wx.key, env.JOB_NAME, Common.cicdYamlData.envData.envName, false)
        }
      }
    }
  }
}